package com.sakura.oj.service.impl;

import cn.hutool.json.JSONException;
import cn.hutool.json.JSONUtil;
import com.sakura.oj.common.ErrorCode;
import com.sakura.oj.exception.BusinessException;
import com.sakura.oj.model.dto.user.UserLoginRequest;
import com.sakura.oj.model.vo.LoginUserVO;
import com.sakura.oj.service.AuthStrategy;
import com.sakura.oj.service.UserService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 账号密码认证策略
 *
 * @author sakura
 */
@Service(AuthStrategy.AUTH_BASE_KEY + "password")
public class PasswordAuthStrategy implements AuthStrategy {

    @Resource
    private UserService userService;

    @Override
    public LoginUserVO login(String data) {
        // 1. 解析data  会出现解析异常
        UserLoginRequest userLoginRequest = null;
        try {
            userLoginRequest = JSONUtil.toBean(data, UserLoginRequest.class);
        } catch (JSONException e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (ObjectUtils.isEmpty(userLoginRequest)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数未传递");
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();

        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数未传递");
        }

        return userService.userLogin(userAccount, userPassword);
    }
}
